<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validate-trigger="submit" err-show-type="toast">
			<uni-forms-item name="title" label="标题" required>
				<textarea @input="binddata('title', $event.detail.value)" class="uni-textarea-border"
					v-model="formData.title" trim="right"></textarea>
			</uni-forms-item>
			<uni-forms-item name="content" label="帖子内容" required>
				<textarea maxlength = '-1' @input="binddata('content', $event.detail.value)" class="uni-textarea-border"
					v-model="formData.content" trim="right"></textarea>
			</uni-forms-item>
			<uni-forms-item name="imgs" label="图片列表">
				<uni-file-picker file-mediatype="image" :limit="6" return-type="array" v-model="formData.imgs">
				</uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="category_id" label="帖子类别" required>
				 <uni-data-select
				      collection="NeuHelper-PostCategories"
				      field="name as text,  _id as value"
				      label="帖子类别"
				      v-model="formData.category_id"
				      :clear="false"
			/>
			</uni-forms-item> 
			<uni-forms-item v-if="formData.category_id=='642d7f6ce766bb2975cd4dfb'" name="author" label="作者">
				<uni-easyinput v-model="formData.author" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item v-else name="contacts" label="联系方式">
				<uni-easyinput v-model="formData.contacts" trim="both"></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="submit">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '@/uni_modules/uni-feedback/js_sdk/validator/opendb-feedback.js';
	console.log(validator);
	const db = uniCloud.database();
	const dbCollectionName = 'NeuHelper-Posts';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			let formData = {
				"title":"",
				"content": "",
				"imgs": [],
				"category_id":"",
				"contacts": "",
				"author":""
			}
			let emptyData = {
				"title":"",
				"content": "",
				"imgs": [],
				"category_id":"",
				"contacts": "",
				"author":""
			}
			return {
				current_post_id:'',
				publish_date:'',
				formData,
				emptyData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				},
				current_userID:'' ,// 当前登录用户ID
				editOK:false,
				current_post_userID:'' // 当前帖子用户ID
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		//post_id,post_content,post_title
		async onLoad(options) {
			console.log('编辑页面')
			console.log(options)
			//await this.getCurrentUserID() // 获取当前用户ID ,异步需要await 等待结果
		//	await this.getPostUserID(options.postId)

			this.formData.content = options.post_content
			this.formData.title = options.post_title
			this.current_post_id = options.postId
			// 4.14 原始图片信息无法通过传递参数过来，需要查表获取
			let imgsData =await db.collection("NeuHelper-Posts").where("_id=='" + this.current_post_id  + "'").field("imgs").get()
			imgsData = imgsData.result.data[0].imgs
			console.log(imgsData)
			this.formData.imgs = imgsData
		},
		methods: {
			async getPostUserID(postId){
				let userID =await db.collection("NeuHelper-Posts").where("_id=='" + postId  + "'").field("user_id").get()
				userID = userID.result.data[0].user_id
				this.current_post_userID = userID
			},
			async getCurrentUserID(){
				let userID =await db.collection("uni-id-users").where("_id == $cloudEnv_uid").field("_id").get()
				userID = userID.result.data[0]._id 
				this.current_userID = userID
			},
			/**
			 * 触发表单提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					this.submitForm(res)
				}).catch(() => {
					uni.hideLoading()
				})
			},

			submitForm(value) {
				db.collection("NeuHelper-Posts").where("_id=='" + this.current_post_id  + "'")
				.update(value).then((res) => {
					uni.showToast({
						icon: 'none',
						title: '提交成功'
					})
					// 更新最后修改时间
					db.collection("NeuHelper-Posts").where("_id=='" + this.current_post_id  + "'")
					.update({'last_modify_date':Date.now()}) 
					// 重新刷新
					this.formData = this.emptyData;
					setTimeout(() => uni.navigateBack(), 500) // 返回
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			//两个方式留作扩展
			submitInquiry(value){
				
			},
			submitCampus(value){
				
			}
		}
	}
</script>

<style>
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;

	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
		padding: 12px 20px;
		font-size: 14px;
		border-radius: 4px;
		line-height: 1;
		margin: 0;
	}
</style>
